<template>
  <el-config-provider :locale="zhCn">
  <div class="page">
    <div class="toolbar">
      <el-form :inline="true" class="filters">
        <el-form-item label="搜索"><el-input v-model="q" placeholder="按编号/名称搜索" style="width:240px" /></el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reload">查询</el-button>
          <el-button @click="openCreate">新建</el-button>
        </el-form-item>
      </el-form>
      <div class="actions"></div>
    </div>
    <div class="table-area">
      <div class="table-container">
        <el-table :data="rows" style="width:100%" max-height="100%">
          <el-table-column prop="code" label="报告编号" min-width="180" />
          <el-table-column prop="name" label="报告名称" min-width="220" />
          <el-table-column label="评估模板" min-width="180">
            <template #default="{ row }">{{ row.adopted_template || '-' }}</template>
          </el-table-column>
          <el-table-column label="采用版本号" width="120">
            <template #default="{ row }">{{ row.adopted_version_no ?? '-' }}</template>
          </el-table-column>
          <el-table-column label="操作" width="320" fixed="right">
            <template #default="{ row }">
              <el-button @click="openEdit(row)">编辑</el-button>
              <el-button @click="goVersions(row)">版本列表</el-button>
              <el-popconfirm title="确定删除该报告？" @confirm="remove(row)">
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper, total"
            :total="total"
            :page-size="pageSize"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            @size-change="onSizeChange"
            @current-change="onPageChange"
          />
        </el-config-provider>
      </div>
    </div>
    <el-dialog v-model="showEdit" title="编辑报告">
      <el-form label-width="100px">
        <el-form-item label="编号"><el-input v-model="form.code" disabled /></el-form-item>
        <el-form-item label="名称"><el-input v-model="form.name" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showCreate" title="新建报告">
      <el-form label-width="100px">
        <el-form-item label="编号"><el-input v-model="createForm.code" /></el-form-item>
        <el-form-item label="名称"><el-input v-model="createForm.name" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreate=false">取消</el-button>
        <el-button type="primary" @click="create">创建</el-button>
      </template>
    </el-dialog>
  </div>
  </el-config-provider>
  </template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { api } from '../../api/client'
import { useRouter } from 'vue-router'

const router = useRouter()
const q = ref('')
const rows = ref<any[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showEdit = ref(false)
const showCreate = ref(false)
const form = ref<any>({ id:'', code:'', name:'' })
const createForm = ref<any>({ code:'', name:'' })

async function load() {
  const res0 = await api.get('/report-headers/', { params: { q: q.value, page: page.value, page_size: pageSize.value } })
  const data0 = res0.data
  const res: any[] = Array.isArray(data0.items) ? data0.items : Array.isArray(data0) ? data0 : []
  total.value = typeof data0.total === 'number' ? data0.total : res.length
  const ids = res.map(r => r.adopted_version_id).filter(Boolean)
  let adopted: Record<string, any> = {}
  if (ids.length) {
    const list = await Promise.all(ids.map(id => api.get(`/report-versions/${id}`)))
    list.forEach(resp => {
      const v = resp.data
      adopted[v.report_id] = { template: v.template_version_code, version_no: v.version_no }
    })
  }
  rows.value = res.map(r => ({
    ...r,
    adopted_template: adopted[r.id]?.template,
    adopted_version_no: adopted[r.id]?.version_no,
  }))
}

function reload(){
  page.value = 1
  load()
}

function openEdit(row:any){
  form.value = { id: row.id, code: row.code, name: row.name }
  showEdit.value = true
}

async function save(){
  await api.put(`/report-headers/${form.value.id}`, { name: form.value.name })
  showEdit.value = false
  await load()
}

function openCreate(){
  createForm.value = { code:'', name:'' }
  showCreate.value = true
}

async function create(){
  await api.post('/report-headers/', createForm.value)
  showCreate.value = false
  await load()
}

async function remove(row:any){
  await api.delete(`/report-headers/${row.id}`)
  await load()
}

function goVersions(row:any){
  router.push(`/admin/report-headers/${row.id}/versions`)
}

onMounted(load)
</script>

<style scoped>
.page { 
  height: 100%; 
  display: flex; 
  flex-direction: column; 
  box-sizing: border-box;
  overflow: hidden;
}
.toolbar { 
  flex-shrink: 0; 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  gap: 12px; 
  padding-bottom: 16px; 
  box-sizing: border-box;
}
.filters { flex: 1; }
.actions { flex-shrink: 0; }
.table-area { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  min-height: 0;
  overflow: hidden;
}
.table-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}
.table-container :deep(.el-table) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}
.table-container :deep(.el-table__inner-wrapper) {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  flex: 1;
}
.table-container :deep(.el-table__header-wrapper) {
  flex-shrink: 0;
  height: auto !important;
}
.table-container :deep(.el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto !important;
  height: auto !important;
  min-height: 200px;
}
.table-container :deep(.el-table__empty-block) {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pagination { 
  flex-shrink: 0; 
  display: flex; 
  justify-content: flex-end; 
  padding-top: 16px; 
  padding-bottom: 8px;
  box-sizing: border-box;
  background: white;
  border-top: 1px solid #f0f0f0;
  margin-top: auto;
}
@media (max-width: 768px) {
  .toolbar { flex-direction: column; align-items: stretch; }
  .filters { margin-bottom: 12px; }
  .pagination { justify-content: center; }
}
</style>